<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/25
 * Time: 20:02
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\DAO\UserProceeds;
use common\models\DAO\UserRate;
use common\models\DAO\UserRateLog;
use common\msg\UserMsg;
use frontend\models\Service\UserInvestService;

class MyAccount {
    public static function current($userInfo){


        $userID = $userInfo['userID'];

        $result = array();
        //昨日收益
        $result['last_accural'] = CommonFunction::formatMoney(Wallet::getAccrual($userID));

        //累计收益
        $result['total_accural'] = CommonFunction::formatMoney(Wallet::tatalAccrual($userID));

        //账户余额
        $result['remainder'] = CommonFunction::formatMoney(Wallet::remainder($userID));

        //用户活期券
        $user_rate = DayService::getAppCurRate($userID);

        //年利率
        $rate = DayService::getRate();
        $result['rate'] = CommonFunction::formatMoney($rate + $user_rate['rate']);
        $rate = $rate / 100;
        $user_rate['user_rate'] = CommonFunction::formatMoney($user_rate['rate']);
        $result['user_rate'] = $user_rate;

        $result['account'] = substr($userInfo['tel'],  0, 3) . '****' . substr($userInfo['tel'],  -4, 4);
        $db = \Yii::$app->db;
        $rate_result = $db
            ->createCommand("SELECT * FROM (SELECT FROM_UNIXTIME(createTime, '%Y%m%d') as d,loseTime, rate,createTime
                FROM  `p2p_user_rate_log` WHERE `userID`= {$userID} ORDER BY `id` DESC LIMIT 0,5) u GROUP BY u.`d` ORDER BY u.`d` DESC")->query()->readAll();
        $user_rate = [];
        $today = date("Y-m-d");
        if($rate_result){
            foreach($rate_result as $k=>$v){
                if(count($user_rate) >= 5)
                    break;
                $loseTime = date('Y-m-d',strtotime($v['loseTime']));
                if(isset($createTime) && $loseTime < $createTime){
                    $user_rate[$loseTime] = $rate;
                }
                $createTime = date('Y-m-d',$v['createTime']);
                $user_rate[$createTime] = $rate + $v['rate']/100;
                if($createTime < $today && $k == 0){
                    if($today < $loseTime){
                        $user_rate[$today] = $rate + $v['rate']/100;
                    }else
                        $user_rate[$today] = $rate;
                }
            }

        }
        ksort($user_rate);
        while(count($user_rate) < 5){
            if(!$user_rate)
                $user_rate[date("Y-m-d",strtotime("-4 day"))] = $rate;
            else{
                $key = array_keys($user_rate)[0];
                $user_rate[date("Y-m-d",strtotime($key) - 24*60*60)] = $rate;
                ksort($user_rate);
            }
        }
        $result['rate_list'] = $user_rate;
        $user_proceeds = [];
        $proceeds = UserProceeds::find()->where(['userID'=>$userID])->limit(5)->orderBy('id desc')->all();
        foreach($proceeds as $v)
            $user_proceeds[date('Y-m-d',strtotime($v['createTime']))] = CommonFunction::formatMoney($v['money']);
        ksort($user_proceeds);
        while(count($user_proceeds) < 5){
            if(!$user_proceeds)
                $user_proceeds[date("Y-m-d",strtotime("-4 day"))] = '0.00';
            else{
                $key = array_keys($user_proceeds)[0];
                $user_proceeds[date("Y-m-d",strtotime($key) - 24*60*60)] = '0.00';
                ksort($user_proceeds);
            }
        }
        $result['proceeds_list'] = $user_proceeds;

        return $result;
    }

    public static function app_init($userInfo){

        $userID = $userInfo['userID'];

        $result = array();

        //账户余额
        $remainder = Wallet::remainder($userID);

        //预计计息 本金
        $pre_invest = InvestService::preInvest($userID);
        //投资总额
        $result['pre_invest'] = CommonFunction::formatWan($pre_invest['money']);
        //投资收益
        $result['pre_accrual'] = CommonFunction::formatMoney($pre_invest['accrual']);

        $result['total_account'] = CommonFunction::formatMoney($pre_invest['money'] + $pre_invest['accrual'] + $remainder);

        return $result;
    }

    public static function init($userInfo){

        $userID = $userInfo['userID'];

        $result = array();
        //昨日收益
        $result['last_accural'] = CommonFunction::formatMoney(Wallet::getAccrual($userID));

        //累计收益
        $result['total_accural'] = CommonFunction::formatMoney(Wallet::tatalAccrual($userID));

        //账户余额
        $result['remainder'] = CommonFunction::formatMoney(Wallet::remainder($userID));

        //账户冻结资金
        $result['freeze'] = CommonFunction::formatMoney(Wallet::freeze($userID));

        //年利率
        $result['rate'] = DayService::getRate() / 100;

        $result['user_rate'] = CommonFunction::formatMoney(DayService::getCurRate($userID));

        $invest_total = InvestService::total($userID);
        //投资总额
        $result['invest'] = CommonFunction::formatWan($invest_total['money']);
        //投资收益
        $result['accrual'] = CommonFunction::formatMoney($invest_total['accrual']);

        //预计计息 本金
        $pre_invest = InvestService::preInvest($userID);
        //本息
        $result['pre_invest_total'] = CommonFunction::formatWan(intval($pre_invest['money']) + intval($pre_invest['accrual']));
        //投资总额
        $result['pre_invest'] = CommonFunction::formatWan($pre_invest['money']);
        //投资收益
        $result['pre_accrual'] = CommonFunction::formatMoney($pre_invest['accrual']);

        $result['account'] = substr($userInfo['tel'],  0, 3) . '****' . substr($userInfo['tel'],  -4, 4);
        return $result;
    }


    public static function simple($userInfo){
        $userID = $userInfo['userID'];

        $result = array();
        //昨日收益
        $result['last_accural'] = CommonFunction::formatWan(Wallet::getAccrual($userID));
        //账户余额
        $result['remainder'] = CommonFunction::formatWan(Wallet::remainder($userID));

        $invest_total = InvestService::total($userID);
        //投资总额
        $result['invest'] = CommonFunction::formatWan($invest_total['money']);
        //投资收益
        $result['accrual'] = CommonFunction::formatWan($invest_total['accrual']);
        $result['day'] = ProductService::setting(1)['setting'];
        $result['month'] = ProductService::setting(2)['setting'];
        $result['account'] = substr($userInfo['tel'],  0, 3) . '****' . substr($userInfo['tel'],  -4, 4);
        return $result;
    }

    public static function getRate($userID){
        $now = date('Ymd');
        $time = strtotime($now);
        $list = [];
        $result = UserRate::find()->where(['userID'=>$userID])->andWhere("$now<loseTime")->orderBy('loseTime asc')->all();
        if($result){
            foreach($result as $v){
                //var_dump((strtotime($v['loseTime']) - time())/24/3600);die;
                $coupon['day'] =  (strtotime($v['loseTime']) - $time)/24/3600 - 1;
                if($coupon['day'] <= 0){
                    $coupon['day'] = intval((strtotime($v['loseTime']) - time())/3600) . '小时';
                }else
                    $coupon['day'] = $coupon['day'].'天';
                $coupon['rate'] = CommonFunction::formatMoney($v['rate']);
                $coupon['id'] = $v['id'];
                $coupon['status'] = $v['status'];
                $list[] = $coupon;
            }
        }
        return $list;
    }

    public static function useRate($userID, $id){
        $rate_info = UserRate::findOne($id);
        $result = ['status'=>0, 'msg'=>UserMsg::$time_out];
        if(!$rate_info || date('Ymd') >= $rate_info['loseTime']){
            $result['msg'] = UserMsg::$no_rate;
            return $result;
        }
        $day_rate = CommonFunction::formatMoney(intval($rate_info['rate']));
        if($rate_info['status'] == 1)
            return ['status'=>1, 'rate'=>$day_rate];

        $transaction = \Yii::$app->db->beginTransaction();
        $rateModel = new UserRate();
        $rateModel->updateAll(['status'=>2], 'status!=2 and userID='.$userID);
        $rate_info->status = 1;
        $rate_result = $rate_info->save();
        if(!$rate_result){
            $transaction->rollBack();
            return $result;
        }
        $rateLog = new UserRateLog();
        $rateLog->rateID = $id;
        $rateLog->userID = $userID;
        $rateLog->rate = $rate_info['rate'];
        $rateLog->createTime = time();
        $rateLog->loseTime = $rate_info['loseTime'];
        $rateLog->activeID = $rate_info['composeID'];
        $rateLog->typeID = $rate_info['typeID'];
        $log_result = $rateLog->save();

        if(!$log_result){
            $transaction->rollBack();
            return $result;
        }
        $transaction->commit();
        return ['status'=>1, 'rate'=>$day_rate];
    }

    public static function myQrcode($appKey){
        return CommonFunction::encrypt($appKey.'+'.time());
    }
}